//
//  ClubGameDetailCommitListVC.swift
//  77Club
//
//  Created by Apple on 2024/9/4.
//

import UIKit
import JXSegmentedView
import ZLPhotoBrowser

class ClubGameDetailCommitListVC: ClubBaseViewController {

    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubGameDetailCommitCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 150.0.Scale
        return tableView
    }()
    var topModel: ClubGameDetailModel?
    private var emptyView = ClubGameCommitEmptyView()
    
    private var pageIndex = 1
    private var commentList:[ClubGameDetailCommentListModel] = []
    
    var gameId: String = "" {
        didSet{
            loadData()
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .clear
        
        view.subviews{
            tableView
            emptyView
        }
        
        tableView.fillContainer()
        emptyView.leading(0).trailing(0).top(195.0.Scale).height(300)
        tableView.refresh_loadMore {
            self.loadMoreData()
        }.refresh_pull {
            self.loadNewData()
        }
        emptyView.isHidden = true
        emptyView.commitBlock = {
            
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                let commitVC = ClubGamesCommitViewController()
                commitVC.gameId = self.gameId
                commitVC.topModel = self.topModel
                commitVC.updateDataBlock = {
                    DispatchQueue.main.async {
                        NotificationCenter.default.post(name: .updateDetailCommitData, object: nil)
                    }
                    self.loadData()
                }
                self.present(commitVC, animated: true)
            }else{
                self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
            }
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(updateComitData), name: .updateCommitListData, object: nil)
    }
    
    @objc private func updateComitData(){
        self.loadData()
    }
}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension ClubGameDetailCommitListVC: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        commentList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubGameDetailCommitCell", for: indexPath) as! ClubGameDetailCommitCell
        cell.model = self.commentList[indexPath.row]
//        cell.didSelectImage = { index,images in
//            self.selectImage(index: index, images: images)
//        }
//        cell.didSelectVideo = { url in
//            self.selectVideo(url: url)
//        }
        cell.clickLikeBlock = { id in
            self.likeCommit(commitID: id)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
//        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
//
//        }else{
//            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
//        }
        let detailVC = ClubGameDetailCommitDetailVC()
        detailVC.gameID = gameId
        detailVC.gid = self.commentList[indexPath.row].id
        detailVC.updateDataBlock = {
            self.loadData()
        }
        self.navigationController?.pushViewController(detailVC, animated: true)
    }
}

//MARK: action
extension ClubGameDetailCommitListVC {
    
    private func selectImage(index: Int, images: [String]) {
        
        var datas: [Any] = []
        for a in images {
            datas.append(URL(string: a)!)
        }
        let vc = ZLImagePreviewController(datas: datas, index: index, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .image
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    private func selectVideo(url: String) {
        
        let vc = ZLImagePreviewController(datas: [URL(string: url)!], index: 0, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .video
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
}

//MARK: data
extension ClubGameDetailCommitListVC {

    private func loadData(){
        
        ToastUtil.show()
        Task{
            let res = await self.network.request(.commitList(gameId: self.gameId, page: self.pageIndex, sortby: "0"),type: ClubGameDetailCommentListModel.self)
            ToastUtil.dismiss()
            tableView.refresh_end()
            if res.isSuccess, let models = res.models {
                self.emptyView.isHidden = models.count > 0
                self.commentList = models
                self.tableView.reloadData()
            }
        }
    }
 
    private func loadMoreData() {
        pageIndex += 1
        Task{
            let res = await self.network.request(.commitList(gameId: self.gameId, page: self.pageIndex, sortby: "0"),type: ClubGameDetailCommentListModel.self)
            tableView.refresh_end()
            if res.isSuccess, let models = res.models {
                self.commentList.append(contentsOf: models)
                self.tableView.reloadData()
            }
        }
    }
    
    private func loadNewData() {
        pageIndex = 1
        loadData()
    }
    
    private func likeCommit(commitID: String){
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            Task{
                let res = await self.network.request(.likeGameCommit(commitID: commitID))
                if res.isSuccess {
                    loadData()
                }
            }
        }else{
            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
}

extension ClubGameDetailCommitListVC:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
